import React, { useState, useRef, useEffect } from 'react';
import { AppScreen, SavedGameMeta, GameData } from '../types';
import { getSavedGamesMeta, deleteGame, importGame, saveGame, duplicateGame, ensureDefaultTestGameExists, loadGame, exportGame } from '../services/gameSaveService';
import Modal from './Modal';
import { DEFAULT_TEST_GAME_ID } from '../constants';
import WelcomeGuide from './WelcomeGuide';

interface MainMenuProps {
  setCurrentScreen: (screen: AppScreen) => void;
  loadSavedGame: (gameData: GameData) => void;
  showToast: (message: string, type?: 'success' | 'error') => void;
  onStartGuide: () => void;
  onGoToSettings: () => void;
}

const ArrowUpTrayIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" {...props}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
  </svg>
);
const DocumentDuplicateIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" {...props}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 01-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 011.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 00-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 01-1.125-1.125v-9.25m9.75 0h-3.25c-.621 0-1.125.504-1.125 1.125v7.5c0 .621.504 1.125 1.125 1.125h3.25c.621 0 1.125-.504 1.125-1.125v-7.5a1.125 1.125 0 00-1.125-1.125z" />
  </svg>
);

const ArrowDownTrayIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" {...props}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
  </svg>
);

const QuestionMarkCircleIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" {...props}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9 5.25h.008v.008H12v-.008z" />
    </svg>
);


const MainMenu: React.FC<MainMenuProps> = ({ setCurrentScreen, loadSavedGame, showToast, onStartGuide, onGoToSettings }) => {
  const [savedGames, setSavedGames] = useState<SavedGameMeta[]>([]);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<SavedGameMeta | null>(null);
  const [showWelcomeGuide, setShowWelcomeGuide] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [loadedGames, setLoadedGames] = useState<{[key: string]: GameData | null}>({});

  const refreshSavedGames = async () => {
    const gamesMeta = await getSavedGamesMeta();
    setSavedGames(gamesMeta);
  };

  useEffect(() => {
    const init = async () => {
      await ensureDefaultTestGameExists();
      await refreshSavedGames();
    };
    init();
  }, []);
  
  // Preload game data for faster access on click
  useEffect(() => {
    const preloadGames = async () => {
      const gamesToLoad = savedGames.filter(g => !loadedGames[g.id]);
      if (gamesToLoad.length > 0) {
        const loaded = await Promise.all(gamesToLoad.map(g => loadGame(g.id)));
        setLoadedGames(prev => {
          const newLoadedGames = {...prev};
          gamesToLoad.forEach((g, i) => {
            newLoadedGames[g.id] = loaded[i];
          });
          return newLoadedGames;
        });
      }
    }
    if(savedGames.length > 0) {
        preloadGames();
    }
  }, [savedGames]);


  const handleDelete = async (gameId: string) => {
    await deleteGame(gameId);
    await refreshSavedGames();
    setShowDeleteConfirm(null);
    showToast("游戏已删除。", "success");
  };

  const handleDuplicate = async (gameId: string) => {
    const newGame = await duplicateGame(gameId);
    if (newGame) {
      await refreshSavedGames();
      showToast(`游戏 "${newGame.rulebook.gameName}" 已成功复制！`, "success");
    } else {
      showToast("复制游戏失败。", "error");
    }
  };

  const handleExport = async (gameId: string) => {
    const gameData = await loadGame(gameId);
    if (gameData) {
      exportGame(gameData);
      showToast("游戏存档已导出。", "success");
    } else {
      showToast("导出失败：无法加载游戏数据。", "error");
    }
  };

  const handleImportGame = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      try {
        const gameData = await importGame(file);
        await saveGame(gameData); // Save it to local storage as well
        await refreshSavedGames();
        showToast(`游戏 "${gameData.rulebook.gameName}" 已成功导入并保存！`, "success");
      } catch (error) {
        if (error instanceof Error) {
            showToast(`导入失败: ${error.message}`, "error");
        } else {
            showToast("导入失败: 未知错误。", "error");
        }
      }
      // Reset file input value to allow importing the same file again
      if(fileInputRef.current) fileInputRef.current.value = "";
    }
  };

  return (
    <div className="min-h-screen flex flex-col items-center justify-center p-4 bg-gray-900 text-gray-100">
      <header className="mb-12 text-center">
        <h1 className="text-5xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-blue-400 via-purple-500 to-pink-500">
          动态文字AI JRPG
        </h1>
        <p className="text-gray-400 mt-2">与AI共同创造你的传奇故事</p>
      </header>

      <div className="w-full max-w-md space-y-4">
        <button
          data-guide-id="create-game-btn"
          onClick={() => setCurrentScreen(AppScreen.CreateGame)}
          className="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-6 rounded-lg shadow-lg transition-transform transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75"
        >
          创建新游戏
        </button>
        
        <input
          type="file"
          accept=".json"
          ref={fileInputRef}
          onChange={handleImportGame}
          className="hidden"
          id="import-game-input"
        />
        <label
          data-guide-id="import-game-btn"
          htmlFor="import-game-input"
          className="w-full bg-green-600 hover:bg-green-700 text-white font-semibold py-3 px-6 rounded-lg shadow-lg transition-transform transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-green-400 focus:ring-opacity-75 cursor-pointer flex items-center justify-center space-x-2"
        >
          <ArrowUpTrayIcon className="w-5 h-5" />
          <span>导入游戏存档</span>
        </label>

        <button
          onClick={() => setShowWelcomeGuide(true)}
          className="w-full bg-teal-600 hover:bg-teal-700 text-white font-semibold py-3 px-6 rounded-lg shadow-lg transition-transform transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-teal-400 focus:ring-opacity-75 flex items-center justify-center space-x-2"
        >
            <QuestionMarkCircleIcon className="w-6 h-6" />
            <span>新手引导</span>
        </button>

        <button
          data-guide-id="settings-btn"
          onClick={onGoToSettings}
          className="w-full bg-gray-600 hover:bg-gray-700 text-white font-semibold py-3 px-6 rounded-lg shadow-lg transition-transform transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-opacity-75"
        >
          设置
        </button>
      </div>

      {savedGames.length > 0 && (
        <div className="mt-12 w-full max-w-2xl"> {/* Increased max-width for wider buttons */}
          <h2 className="text-2xl font-semibold mb-4 text-gray-300 text-center sm:text-left">继续游戏</h2>
          <div className="space-y-3 max-h-72 overflow-y-auto pr-2"> {/* Increased max-height */}
            {savedGames.map((game) => (
              <div
                key={game.id}
                className={`p-4 rounded-lg shadow-md flex flex-col sm:flex-row justify-between items-center space-y-2 sm:space-y-0 ${game.isDefaultTestGame ? 'bg-teal-800 border-l-4 border-teal-500' : 'bg-gray-800'}`}
              >
                <div className="flex-grow">
                  <h3 className={`text-lg font-medium ${game.isDefaultTestGame ? 'text-teal-300' : 'text-blue-400'}`}>
                    {game.name} 
                    {game.isDefaultTestGame && <span className="text-xs ml-2 px-1.5 py-0.5 bg-teal-600 rounded-full">测试存档</span>}
                  </h3>
                  <p className="text-xs text-gray-500">上次游玩: {game.lastPlayedTimestamp === 0 ? "从未玩过" : new Date(game.lastPlayedTimestamp).toLocaleString('zh-CN')}</p>
                   {game.originalGameId && <p className="text-xs text-gray-500 italic">源自: {loadedGames[game.originalGameId]?.rulebook.gameName || '未知存档'}</p>}
                </div>
                <div className="flex space-x-1 sm:space-x-2 flex-shrink-0">
                  <button
                    onClick={async () => {
                      const fullGame = await loadGame(game.id);
                      if (fullGame) {
                        loadSavedGame(fullGame);
                      } else {
                        showToast("加载游戏失败: 未找到存档数据。", "error");
                      }
                    }}
                    className="px-3 py-1 bg-green-500 hover:bg-green-600 text-white text-sm rounded transition-colors"
                    title="载入游戏"
                  >
                    载入
                  </button>
                  <button
                    onClick={() => handleDuplicate(game.id)}
                    className="px-3 py-1 bg-sky-500 hover:bg-sky-600 text-white text-sm rounded transition-colors flex items-center"
                    title="复制游戏存档"
                  >
                    <DocumentDuplicateIcon className="w-4 h-4 mr-1 sm:mr-0"/> <span className="sm:hidden">复制</span>
                  </button>
                   <button
                    onClick={() => handleExport(game.id)}
                    className="px-3 py-1 bg-indigo-500 hover:bg-indigo-600 text-white text-sm rounded transition-colors flex items-center"
                    title="导出游戏存档"
                  >
                    <ArrowDownTrayIcon className="w-4 h-4 mr-1 sm:mr-0" /> <span className="sm:hidden">导出</span>
                  </button>
                  <button
                    onClick={() => setShowDeleteConfirm(game)}
                    className="px-3 py-1 bg-red-500 hover:bg-red-600 text-white text-sm rounded transition-colors"
                     disabled={game.isDefaultTestGame && game.id === DEFAULT_TEST_GAME_ID} // Disable delete for the specific default test game ID
                     title={game.isDefaultTestGame && game.id === DEFAULT_TEST_GAME_ID ? "默认测试存档无法删除" : "删除游戏"}
                  >
                    删除
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
      <Modal
        isOpen={!!showDeleteConfirm}
        onClose={() => setShowDeleteConfirm(null)}
        title="确认删除"
      >
        <p>你确定要删除游戏 “{showDeleteConfirm?.name}” 吗？此操作无法撤销。</p>
        <div className="mt-6 flex justify-end space-x-3">
          <button
            onClick={() => setShowDeleteConfirm(null)}
            className="px-4 py-2 bg-gray-600 hover:bg-gray-700 rounded text-white transition-colors"
          >
            取消
          </button>
          <button
            onClick={() => showDeleteConfirm && handleDelete(showDeleteConfirm.id)}
            className="px-4 py-2 bg-red-600 hover:bg-red-700 rounded text-white transition-colors"
          >
            确认删除
          </button>
        </div>
      </Modal>
      <WelcomeGuide 
        isOpen={showWelcomeGuide} 
        onClose={() => setShowWelcomeGuide(false)}
        onStartInteractiveGuide={() => {
            setShowWelcomeGuide(false);
            onStartGuide();
        }}
    />
    </div>
  );
};

export default MainMenu;